package com.soulapp.hook

import android.content.Context
import android.widget.Toast
import com.highcapable.yukihookapi.YukiHookAPI
import com.highcapable.yukihookapi.annotation.xposed.InjectYukiHookWithXposed
import com.highcapable.yukihookapi.hook.factory.configs
import com.highcapable.yukihookapi.hook.factory.encase
import com.highcapable.yukihookapi.hook.xposed.proxy.IYukiHookXposedInit
import com.soulapp.data.ConfigData
import com.soulapp.hook.hooker.BaseHooker
import com.soulapp.hook.hooker.SoulMenuHook


@InjectYukiHookWithXposed
class HookEntry : IYukiHookXposedInit {
    private val hookPackageName: String = "cn.soulapp.android"

    override fun onInit() = configs {
        debugLog {
            tag = "SoulHook"
        }
        isDebug = false
    }

    private fun checkApp(context: Context, packageName: String) {
        val packageInfo = context.packageManager.getPackageInfo(packageName, 0)
        val versionName = packageInfo.versionName
        val versionCode = packageInfo.longVersionCode
        if (versionCode != 25081207L) {
            Toast.makeText(context, "请使用v5.86.0版本，当前版本: v${versionName}可能存在兼容性问题！", Toast.LENGTH_SHORT).show()
        }
    }

    fun getMapHooker(): MutableList<BaseHooker> {
        val buildData = SoulMenuHook.buildData()
        val hooker = buildData.map { it.hooker }.toMutableList()
        hooker.add(0, SoulMenuHook)
        return hooker
    }

    override fun onHook() = encase {
        if (!YukiHookAPI.Status.isModuleActive || hookPackageName != packageName) {
            return@encase
        }

        // 判断被hook的app
        loadApp(packageName) {
            onAppLifecycle(false) {
                onCreate {
                    // checkApp(this, packageName)

                    // 初始化配置
                    ConfigData.init(context = this)

                    // 注入hook
                    val mapHooker = getMapHooker()
                    mapHooker.forEach { loadHooker(it) }
                }
            }
        }
    }

}
